package com.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Bean;

import java.util.List;

/**
 * @description:
 * @author: sksun2
 * @create: 2023-09-28
 */
public class GrayRequestInterceptor {

    @Bean
    public RequestInterceptor getRequestInterceptor(DiscoveryClient discoveryClient) {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //discoveryClient中可以找到目前所有的服务实例，含ip&port
                List<ServiceInstance> instances = discoveryClient.getInstances("");


                //requestTemplate 中可以获取到请求参数和url，当前feign的类型等
                String newTarget = "xxx";//这里实现自己的负载均衡算法，可以通过判断当前feign的类型，或者url实现服务的部分接口负载均衡，得到新的target地址
                requestTemplate.target(newTarget);
            }
        };
    }
}
